//
//  HDBMainViewController.swift
//  HDBWeibo
//
//  Created by leidon on 2016/11/17.
//  Copyright © 2016年 BONC. All rights reserved.
//

import UIKit


class HDBMainViewController: UITabBarController {

    lazy var composeButton : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
        
    }

    
    /// 横屏是模式 代码设置 
    /*  
     portrait : 竖屏     landscape ： 横屏
     -使用代码控制设备的方向的好处是可以在需要横屏的时候，单独处理；此处一写 子控制器也遵循 ；视屏的横屏用modal处理
    */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }

}


//MARK: 子控制器（五个主界面）的设置
extension HDBMainViewController {
    
    /// 所有子控制器的设置
      func setupChildControllers()->Void {
        // 注释 ：首先判断是沙盒路径中是否有数据，如果有就使用沙盒中的，如果没有在判断Bundle中的
        
        //获取沙盒路径:
        let docDict = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDict as NSString).appendingPathComponent("main.json")
        var data = NSData.init(contentsOfFile: jsonPath)
        
        print("-------\(jsonPath)")
        
        
        if data == nil {
            let path = Bundle.main.path(forResource: "main.plist", ofType: nil)
            data = NSData.init(contentsOfFile: path!)
        }
        
        
        //路径 -> 加载data -> 反序列化专成数组
        guard let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as? [[String : Any]] else {
           return
        }
        
        
        
        //[Dictionary<String, String>] -> [[String : Any]]
//        let array : [[String : Any]]  = [["className" : "HDBHomeViewController",
//                                          "title" : "首页", "imageName" : "tabbar_home",
//                                          "visitorInfo" : ["imageName" : "","introduce" : "蒹葭苍苍，白露为霜，所谓伊人，在水一方;所谓伊人，在水之湄;所谓伊人，摇手可见；"]],
//                                         
//                     ["className" : "HDBDiscoverViewController",
//                      "title" : "消息", "imageName" : "tabbar_message_center",
//                      "visitorInfo" : ["imageName" : "visitordiscover_image_message","introduce" : "蒹葭苍苍，白露为霜，所谓伊人，在水一方;所谓伊人，在水之湄;所谓伊人，摇手可见；蒹葭采采，蒹葭萋萋"]],
//                     
//                     ["className" : "UIViewController", "title" : "", "imageName" : ""],
//                     
//                     ["className" : "HDBMessageViewController",
//                      "title" : "发现","imageName" : "tabbar_discover",
//                      "visitorInfo" : ["imageName" : "visitordiscover_image_profile","introduce" : "蒹葭苍苍，白露为霜，所谓伊人，在水一方"]],
//                     
//                     ["className" : "HDBProfileViewController",
//                      "title" : "我", "imageName" : "tabbar_profile",
//                      "visitorInfo" : ["imageName" : "visitordiscover_image_profile","introduce" : "蒹葭苍苍，白露为霜，所谓伊人，在水一方;所谓伊人，在水之湄蒹葭采采，蒹葭萋萋"]]]
        
        //数组 -> json
        //let data = try! JSONSerialization.data(withJSONObject: array, options: [])
        //(data as NSData).write(toFile: "/Users/leidon/Desktop/demo.json", atomically: true)
 
        //数组 -> plist
        //(array as NSArray).write(toFile: "/Users/leidon/Desktop/demo.plist", atomically: true)
        
        var arrayM = [UIViewController]()
        //蠢成猪的我  擦擦擦擦
        for dict in array!{
            arrayM.append(controller(dict: dict ))
        }
        viewControllers = arrayM
    }
     
    /// 添加撰写按钮
    func setupComposeButton() {
        let childCount = childViewControllers.count
        let width = tabBar.bounds.width / CGFloat(childCount)
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*width - 1, dy: 0)
        composeButton.addTarget(self, action: #selector(composeClick), for: UIControlEvents.touchUpInside)
        tabBar.addSubview(composeButton)
    }
    
    /// 撰写按钮的方法  -- @objc  只能在当前类中调用，相当于写在OC中的.m文件中
    @objc func composeClick() {
        print("撰写方法")
        
        //XXX : 测试横屏
        let vc = UIViewController()
        vc.view.backgroundColor = #colorLiteral(red: 0.06274510175, green: 0, blue: 0.1921568662, alpha: 1)
        let nac = UINavigationController(rootViewController: vc)
        present(nac, animated: true, completion: nil)
        
//        sleep(2)
        vc.dismiss(animated: true, completion: nil)
    }
    
    /// 根据字典内容创建控制器
    ///
    /// - parameter dict: 字典信息[class, title, imageName]
    ///
    /// - returns: 各个控制器
    private func controller(dict : [String : Any]) ->UIViewController {
        //1> 守护，获取字典内容
        guard let className = dict["className"] as? String,
        let title = dict["title"] as? String ,
        let imageName = dict["imageName"] as? String,
        let cls = NSClassFromString(Bundle.main.namespace + "." + className) as? HDBBaseViewController.Type,
        let dictInfo = dict["visitorInfo"] as? [String : String]
            else {
                return UIViewController()
        }
        //2> 创建vc并分配空间
        let vc = cls.init()
        //3> 设置当前页的title
        vc.title = title
        
        // 给访客视图传参数
        vc.versionInfoDict = dictInfo
        //4>设置当前页tabbar的图片
        vc.tabBarItem.image = UIImage(named:imageName)
        vc.tabBarItem.selectedImage = UIImage(named:imageName + "_highlighted")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        //XXX: 那个点击状态下，tabbar的字体颜色和图片颜色不一样
        //字体默认大小是：12号
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue: 0))
        
        //实例化导航控制器的时候，会调用 push 方法将rootVC压栈
        let nva = HDBNavigationViewController(rootViewController: vc)
        
        return nva
    }
}
